import models.Http;
import models.HttpResponse;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by yangxianming on 2021/1/11.
 */
public class TaskManager implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String appPath = servletContextEvent.getServletContext().getRealPath("/");
        String r = servletContextEvent.getServletContext().getRealPath("/ct");
        System.out.println("----TaskManager----" + r);
        Timer timer = new Timer(true);
        //timer.schedule(new Heartbeat(appPath), 10000, 60000);
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
        try {
//            timer.schedule(new TestBeat(), sdf.parse("2021-03-16 17:30:00"), 86400000);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        Runtime runtime = Runtime.getRuntime();
        try {
//            runtime.exec("TASKKILL /F /IM ding.exe");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

class TestBeat extends TimerTask{
    @Override
    public void run() {
        System.out.println("run testbeat class");
    }
}

//心跳服务器 通过每分钟对主地址做请求验证dingAcross是否还可以工作
//如果不正常就重启dingAcross。测试环境timer.schedule注释掉
class Heartbeat extends TimerTask{
    private String myPath;
    public Heartbeat(String myPath){
        this.myPath = myPath;
    }
    @Override
    public void run() {
        Http http = new Http();
        HttpResponse hr = http.sendRequest("get", null, "http://yxm.vaiwan.com/", "");
        int rd = hr.getrCode();
        System.out.println("http code:" + rd);
        if (rd != 200){
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("TASKKILL /F /IM ding.exe");
                Thread.sleep(2000);
                String dAcrossPath = myPath + "resource\\dingAcross\\";
                String startCom = dAcrossPath+"ding -config=" + dAcrossPath + "ding.cfg -subdomain=yxm 1988";
                System.out.println(startCom);
                //D:\javaWorkSpace\testServer2\web\resource\dingAcross\ding -config=D:\javaWorkSpace\testServer2\web\resource\dingAcross\ding.cfg -subdomain=yxm 1985
                runtime.exec(startCom);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

